﻿namespace IBTrader.Modules.Strategy
{
    using IBTrader.Model;
    using IBTrader.Modules.Market;
    using IBTrader.Modules.Read;
    using System;
    using System.Linq;

    class StrategySwitch
    {
        public event EventHandler<Line> Up, Down;
        public event EventHandler<OrderLine> Enter, Exit;
        private SingleStock strategy;
        private readonly Model.Store store;
        private readonly Market.Order order;
        private readonly int algoId;
        private Algo algo;
        public StrategySwitch(Model.Store store, Market.Order order, int algoId)
        {
            this.store = store;
            this.order = order;
            this.algoId = algoId;
        }
        public void Init(object _, EventArgs __)
        {
            algo = store.Algos.SingleOrDefault(a => a.Id == algoId);
            if (algo == null) return;
            algo.PropertyChanged += (____, e) => { if (e.PropertyName == "Strategy") Switch(); };
            Switch();
        }
        private void Switch()
        {
            if (strategy != null)
            {
                strategy.Up -= Up;
                strategy.Down -= Down;
                strategy.Enter -= Enter;
                strategy.Exit -= Exit;
            }
            if(algo.Strategy == typeof(SwingTrader).Name)
                strategy = new SwingTrader(store, order, algoId);
            else if (algo.Strategy == typeof(TrendFollower).Name)
                strategy = new TrendFollower(store, order, algoId);
            if (strategy != null)
            {
                strategy.Up += Up;
                strategy.Down += Down;
                strategy.Enter += Enter;
                strategy.Exit += Exit;
            }
        }
        public void Bid(object sender, Line line) { if (strategy != null) strategy.Bid(sender, line); }
        public void Ask(object sender, Line line) { if (strategy != null) strategy.Ask(sender, line); }
        public void Hit(object sender, Line line) { if (strategy != null) strategy.Hit(sender, line); }
    }
}
